package com.zcsy.manage.web.base;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * 
 * @Title: CellBuildingController.java
 * @Package： com.zcsy.manage.web.base 
 * @Description: 小区楼栋控制层
 *
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年4月8日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/cellBuilding")
public class CellBuildingController {
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private ICellRegionService cellRegionService;
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	@Autowired
	private ICellHouseService cellHouseService;
	
	@Autowired
	private IDictService dictService;
	
    /**
     * 
     * @Description 返回小区楼栋查询列表
     * 
     * @param model
     * @param pNo 当前页面
     * @param cellid 小区id
     * @param regionid 区域id
     * @param buildingName 楼栋名
     * @param req 用户请求
     * @return 返回小区楼栋查询列表
     * @author lilan 1063972142@qq.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "cellBuildingList", method = RequestMethod.GET)
    public String cellBuildingList(Model model, Integer pNo, Integer pSize, String regionid, String buildingName, HttpServletRequest req){
    	if(pNo == null){
    		pNo = Constants.PAGE_NO;
    	}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        CellBuilding cellBuilding = new CellBuilding();
        
        //获取当前小区信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellid = user.getCurrentCell().getId();
        cellBuilding.setCellId(cellid);
        
        if(StringUtils.isNotEmpty(regionid)){
        	cellBuilding.setRegionId(regionid);
        }
        if(StringUtils.isNotEmpty(buildingName)){
        	cellBuilding.setBuildingName(buildingName);
        }
        
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        
        List<CellBuilding> cellBuildings = cellBuildingService.selectByKeyword(cellBuilding);
        PageInfo<CellBuilding> building = new PageInfo<CellBuilding>(cellBuildings);
        List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellid);
        
        model.addAttribute("cellBuilding",building);
        model.addAttribute("cellRegions", cellRegions);
        model.addAttribute("regionid",regionid);
        model.addAttribute("buildingName",buildingName);
        model.addAttribute("currentPage",pNo);
		model.addAttribute("pSize", pSize);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "base/cellbuilding/cellBuildingList";
    		
    }
    
    /**
     * 
     * @Description 返回或新增小区楼栋页面
     * type=1，新增页面
     * type=2，编辑页面
     * @param model
     * @param id 主键id，id=0新增，id!=0编辑
     * @return 返回新增或编辑小区楼栋页面
     * @author lilan 1063972142@qq.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "editCellBuilding", method = RequestMethod.GET)
    public String editCellBuilding(Model model, String id,HttpServletRequest req){
    	try{
    		if(String.valueOf(Constants.STATE_DISABLED).equals(id)){
    		    
    			model.addAttribute("type",Constants.SAVE_TYPE);
    		} else{
    			CellBuilding cellBuilding = cellBuildingService.selectByPrimaryKey(id);
    			if(cellBuilding != null){
    				model.addAttribute("type",Constants.EDIT_TYPE);
    				model.addAttribute("cellBuilding",cellBuilding);
    				model.addAttribute("buildingcellId",cellBuilding.getCellId());
    				model.addAttribute("buildingregionId",cellBuilding.getRegionId());
    			}
    		}

		    User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
	        String cellid = user.getCurrentCell().getId();
	        List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellid);
	        model.addAttribute("cellRegions", cellRegions);
    	} 
    	catch(Exception e){
    		e.printStackTrace();
    	}
    	
    	return "base/cellbuilding/cellBuildingEdit";
    }
    
    /**
     * @Description 保存和更新小区楼栋方法
     * @param model
     * @param id 主键id
     * @param buildingName 楼栋名
     * @param cellid 小区id
     * @param regionid 区域id
     * @param req 用户请求
     * @return 返回结果：1成功，0失败
     * @author lilan 1063972142@qq.com
     * @date 2016年4月8日
     * @see
     */
    @RequestMapping(value = "saveOrUpdateCellBuilding", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdate(Model model, String id, String buildingName, 
    		                        String regionid, Integer sort, String memo, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	String cellid = user.getCurrentCell().getId();
    	CellBuilding cellBuilding = new CellBuilding();
    	cellBuilding.setBuildingName(buildingName);
    	cellBuilding.setUserAccount(user.getLoginname());
    	cellBuilding.setSort(sort);
    	cellBuilding.setMemo(memo);
    	try{
    	    // 检验名称是否存在
            boolean isUpdate = (id != null && !"0".equals(id));
            if(StringUtil.isEmptyString(regionid)) {
                regionid = cellBuildingService.selectByPrimaryKey(id).getRegionId();
            }
            boolean nameExists = cellBuildingService.isNameExists(isUpdate ? id : null, regionid, buildingName);
            if(nameExists) {
                result.setSuccess(false);
                result.setMsg("楼栋名称已存在");
            } else {
                if(isUpdate){
                    cellBuilding.setId(id);
                    cellBuilding.setUpdateTime(new Date());

                    cellBuilding.setRegionId(regionid);
                    if(regionid != null){
                        cellBuilding.setRegionName(cellRegionService.selectByPrimaryKey(regionid).getName());
                    }
                    cellBuildingService.update(cellBuilding);
                    
                    LogUtils.insertLog("小区楼栋信息编辑", user.getId(), req);
                } else{
                    cellBuilding.setCellId(cellid);
                    if(cellid != null){
                        cellBuilding.setCellName(cellInfoService.selectByPrimaryKey(cellid).getCellName());
                    }
                    cellBuilding.setRegionId(regionid);
                    if(regionid != null){
                        cellBuilding.setRegionName(cellRegionService.selectByPrimaryKey(regionid).getName());
                    }
                    
                    cellBuilding.setId(UniqueNumberUtils.get18UniqueNumber());
                    cellBuilding.setSendTime(new Date());
                    cellBuildingService.insert(cellBuilding);
                    LogUtils.insertLog("小区楼栋信息新增", user.getId(), req);
                }
                result.setSuccess(true);
            }
    		
    	}
    	catch(Exception e){
    	    e.printStackTrace();
    	    result.setSuccess(false);
    		result.setMsg("操作失败！");
    	}
    	
    	return result;
    }
    
    /**
     * @Description 根据小区楼栋id删除多条楼栋信息
     * @param ids 小区楼栋对象数组
     * @param req 用户请求
     * @author lilan 1063972142@qq.com
     * @date 2016年4月8日
     * @see
     */
    @RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteByPrimaryKey(String ids, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	try{
    		String keys[] = ids.split("\\,");
    		for (int i = 0; i < keys.length; i++ ) {
    			List<CellUnit> cellUnits = cellUnitService.getCellUnitByBuildingId(keys[i]);
    			CellBuilding cellBuilding = cellBuildingService.selectByPrimaryKey(keys[i]);
    			if(cellUnits.size() == 0){
    				cellBuildingService.deleteByPrimaryKey(keys[i]);
    				result.setSuccess(true);
    				LogUtils.insertLog("小区楼栋信息删除", user.getId(), req);
    			}else{
    				result.setMsg(cellBuilding.getBuildingName() + "楼栋已被引用，不能删除！");
    				result.setSuccess(false);
    			}
    		}
    	} catch (NumberFormatException e) {
    		result.setSuccess(false);
    		result.setMsg("操作失败");
    	}
    	
    	return result;
    }
    
    /**
     * @Description 根据小区id获取小区中相应的区域列表
     * @param cellid 小区id
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年4月8日
     * @see
     */
    @RequestMapping(value = "getCellRegionByCellId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellRegionByCellId(String cellid, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try{
    		List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellid);
    		result.setObj(cellRegions);
    	} catch(Exception e){
    	}
    	
    	return result;
    }

    
	/**
	 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
	 * @param id 商品id
	 * @param req 用户请求
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
        	CellBuilding cellBuilding = cellBuildingService.selectByPrimaryKey(id);
        	if(cellBuilding != null){
        		cellBuilding.setUpdateTime(DateUtils.getDate());
        		cellBuildingService.updateSort(cellBuilding);
        		LogUtils.insertLog("小区楼栋信息置顶", user.getId(), req);
        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
